/*
 * This file is part of quickReminder, a software for gamers
 *
 * Copyright (C) 2006-2008 Lucas Romero
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using Microsoft.Win32;
using LucasCode.UpdateChecker;
using LucasCode.UpdateForm;
using System.Collections;
using XPTable;
using XPTable.Editors;
using XPTable.Models;
using System.Diagnostics;
using UserNotifier;
using System.Xml.Serialization;

namespace quickReminder
{
	/// <summary>
	/// Description of FormSettings.
	/// </summary>
	public partial class FormSettings
	{
        AutoUpdateChecker upd = new AutoUpdateChecker();
        WarnModuleCollection WarnModules = null;
		public FormSettings(ref WarnModuleCollection warnmodules)
		{
            WarnModules = warnmodules;
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
            ttDebugHelp.SetToolTip(cbEnableConsoleParsing, lang.ConsoleDebugEnableHelp);
            ttDebugHelp.SetToolTip(cbOverwriteProtection, lang.OverWriteProtectionHelp);
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}

		private Cookie getLoginCookie(string Username, String Password)
		{
			Cookie cookie=null;
			string HTML = String.Empty;
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.esl.eu/login/save/?duration=forever&email_id=" + Username + "&password=" + Password);
			request.Timeout = 10000;
			request.CookieContainer = new CookieContainer();
			HttpWebResponse response = (HttpWebResponse) request.GetResponse();
			StreamReader answer = new StreamReader(response.GetResponseStream());
			try
			{
				HTML = answer.ReadToEnd();
			}
			catch (Exception ex)
			{
				throw ex;
			}
			finally
			{
				answer.Close();
			}
			if (!Regex.Match(HTML,">Logged in!<").Success)
			{
				//Login not successful
				throw new Exception(lang.PasswordWrong);
			}
			else
			{
				cookie = request.CookieContainer.GetCookies(request.RequestUri)["COOKIE"];
			}

			return cookie;
		}
		
		void RWarnWhenOpenCheckedChanged(object sender, System.EventArgs e)
		{
			pLoginData.Enabled = rWarnWhenOpen.Checked;
		}
		
		void Label1MouseEnter(object sender, System.EventArgs e)
		{
			((Label)sender).BorderStyle = BorderStyle.FixedSingle;
		}
		
		void Label1MouseLeave(object sender, System.EventArgs e)
		{
			((Label)sender).BorderStyle = BorderStyle.None;
		}
		
		void Label1EnabledChanged(object sender, System.EventArgs e)
		{
			bLogout.Enabled = !((Control)sender).Enabled;
			tbUser.Enabled = ((Control)sender).Enabled;
			tbPassword.Enabled = ((Control)sender).Enabled;
			bGetCookie.Enabled = ((Control)sender).Enabled;
		}
		
		void Label1Click(object sender, System.EventArgs e)
		{
			Cookie c;
			((Control)sender).Enabled = false;
			pLoginData.Enabled = false;
			UseWaitCursor = true;
			try
			{
				c = getLoginCookie(tbUser.Text,tbPassword.Text);
				quickReminder.Properties.Settings.Default.Cookie = c.Value;
				MessageBox.Show(lang.LoginSuccessful);
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
				((Control)sender).Enabled = true;
			}
			UseWaitCursor = false;
			pLoginData.Enabled = true;
		}
		
		void BGetCookieClick(object sender, System.EventArgs e)
		{
            using (FormCookieSelect fc = new FormCookieSelect())
            {
                if (fc.ShowDialog() == DialogResult.OK)
                {
                    quickReminder.Properties.Settings.Default.Cookie = fc.Cookie;
                    bLogin.Enabled = false;
                    bLogout.Enabled = true;
                    bGetCookie.Enabled = false;
                }
            }
		}
		
		void BLogoutClick(object sender, System.EventArgs e)
		{
			quickReminder.Properties.Settings.Default.Cookie = string.Empty;
            bLogin.Enabled = true;
		}
		
		void FormSettingsFormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
		{
			quickReminder.Properties.Settings.Default.AlwaysWarn = rWarnAlways.Checked;
            if (!rWarnAlways.Checked && bLogin.Enabled)
			{
				MessageBox.Show(lang.YouMustLogin);
				e.Cancel=true;
			}
		}
		
		void CbAutostartCheckedChanged(object sender, System.EventArgs e)
		{
			Microsoft.Win32.RegistryKey reg;
			reg = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run",true);
			if (cbAutostart.Checked)
				reg.SetValue("quickReminder", "\"" + Application.ExecutablePath + "\"");
			else
				reg.DeleteValue("quickReminder");
			reg.Close();
		}
		
		void Label1MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			((Label)sender).BorderStyle = BorderStyle.Fixed3D;
		}
        protected override void OnClosed(EventArgs e)
        {
            try
            {
                WarnModules.Save("default.qwm");
            }
            catch { };
            Properties.Settings.Default.EnableDebug = cbDebug.Checked;
            Properties.Settings.Default.AutoGatherFiles = cbAutoGatherFiles.Checked;
            Properties.Settings.Default.OverWriteProtectionEnabled = cbOverwriteProtection.Checked;

            Properties.Settings.Default.SetPriorityGame = cbSetPrioGame.Checked;
            Properties.Settings.Default.SetAffinityAequitas = cbSetAffAeq.Checked;
            Properties.Settings.Default.SetAffinityGame = cbSetAffGame.Checked;
            Properties.Settings.Default.SetAffinityquickReminder = cbSetAffReminder.Checked;

            Properties.Settings.Default.AffinityAequitas = CPUSelAeq.SelectedIndex;
            Properties.Settings.Default.AffinityGame = CPUSelGame.SelectedIndex;
            Properties.Settings.Default.AffinityquickReminder = CPUSelReminder.SelectedIndex;

            Properties.Settings.Default.HotkeyNum = (int)HotkeySelector.KeyCode;
            Properties.Settings.Default.HotkeyCtrl = HotkeySelector.Ctrl;
            Properties.Settings.Default.HotkeyAlt = HotkeySelector.Alt;
            Properties.Settings.Default.HotkeyShift = HotkeySelector.Shift;
            Properties.Settings.Default.HotkeyActive = cbActivateHotkey.Checked;

            Properties.Settings.Default.AutoCheckForUpdates = cbAutoUpdate.Checked;

            Properties.Settings.Default.DemoWriteLimit = (int)nDemoWarnTime.Value;

            Properties.Settings.Default.MatchFilter.Clear();
            foreach (ListViewItem i in lwMatchFilter.Items)
                Properties.Settings.Default.MatchFilter.Add(i.Text);

            Properties.Settings.Default.ProcessOptimizerList.Clear();
            foreach (Row r in tableModel1.Rows)
                Properties.Settings.Default.ProcessOptimizerList.Add(r.Cells[0].Text +
                    Properties.Settings.Default.ProcessOptimizerListSplitter +
                    r.Cells[1].Text +
                    Properties.Settings.Default.ProcessOptimizerListSplitter +
                    r.Cells[2].Text +
                    Properties.Settings.Default.ProcessOptimizerListSplitter +
                    r.Cells[3].Checked.ToString());
            Properties.Settings.Default.JPGCompressionQuality = (int)nCompressionQuality.Value;
            Properties.Settings.Default.EnableConsoleParsing = cbEnableConsoleParsing.Checked;
            if (cbLanguageOverride.Checked)
            {
                if (cbLanguage.SelectedIndex == 0)
                    Properties.Settings.Default.LanguageString = "de";
                else if (cbLanguage.SelectedIndex == 1)
                    Properties.Settings.Default.LanguageString = "en";
                else
                    Properties.Settings.Default.LanguageString = string.Empty;
            }
            else
                Properties.Settings.Default.LanguageString = string.Empty;
            Properties.Settings.Default.ArchivePathTemplate = ArchivePattern.Text;
            Properties.Settings.Default.FreeDiskspaceWarnThreshold = (ulong)nFreeDiskspaceTreshold.Value;
            Properties.Settings.Default.CheckQmaAssociation = cbFileAssociation.Checked;
            Properties.Settings.Default.AequitasTitle = tbAequitasName.Text;
            Properties.Settings.Default.Save();
            
            base.OnClosed(e);
            this.Dispose();
        }

        private void cbSetAffGame_CheckedChanged(object sender, EventArgs e)
        {
            CPUSelGame.Enabled = cbSetAffGame.Checked;
        }

        private void cbSetAffReminder_CheckedChanged(object sender, EventArgs e)
        {
            CPUSelReminder.Enabled = cbSetAffReminder.Checked;
        }

        private void cbSetAffAeq_CheckedChanged(object sender, EventArgs e)
        {
            CPUSelAeq.Enabled = cbSetAffAeq.Checked;
        }

        private void FormSettings_Load(object sender, EventArgs e)
        {
            if (quickReminder.Properties.Settings.Default.NewVersionInstalled)
            {
                quickReminder.Properties.Settings.Default.Upgrade();
                quickReminder.Properties.Settings.Default.NewVersionInstalled = false;
            }
            if (quickReminder.Properties.Settings.Default.AlwaysWarn)
            {
                rWarnAlways.Checked = true;
                rWarnWhenOpen.Checked = false;
            }
            else
            {
                rWarnAlways.Checked = false;
                rWarnWhenOpen.Checked = true;
            }
            if (quickReminder.Properties.Settings.Default.Cookie != string.Empty)
                bLogin.Enabled = false;
            Label1EnabledChanged(bLogin, new EventArgs());
            /*Text = gs("Settings");
            //groupBox1.Text = gs("Settings");
            rWarnAlways.Text = gs("WarnAlways");
            cbAutostart.Text = gs("AutoRun");
            rWarnWhenOpen.Text = gs("CheckForOpenMatches");
            bLogout.Text = gs("DeleteCookie");
            bGetCookie.Text = lang.GetString("GetCookie");*/
            table1.NoItemsText = lang.ProcessNoItemText;
            cName.Text = lang.ProcessName;
            cPriority.Text = lang.ProcessPriority;
            Microsoft.Win32.RegistryKey reg;
            reg = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
            if ((string)reg.GetValue("quickReminder") == "\"" + Application.ExecutablePath + "\"")
                cbAutostart.Checked = true;

            CPUSelAeq.Items.Clear();
            CPUSelGame.Items.Clear();
            CPUSelReminder.Items.Clear();
            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                CPUSelAeq.Items.Add("CPU " + i);
                CPUSelGame.Items.Add("CPU " + i);
                CPUSelReminder.Items.Add("CPU " + i);
            }

            HotkeySelector.KeyCode = (Keys)Properties.Settings.Default.HotkeyNum;
            HotkeySelector.Ctrl = Properties.Settings.Default.HotkeyCtrl;
            HotkeySelector.Alt = Properties.Settings.Default.HotkeyAlt;
            HotkeySelector.Shift = Properties.Settings.Default.HotkeyShift;
            cbActivateHotkey.Checked = Properties.Settings.Default.HotkeyActive;


            cbDebug.Checked = quickReminder.Properties.Settings.Default.EnableDebug;
            cbAutoGatherFiles.Checked = Properties.Settings.Default.AutoGatherFiles;
            cbOverwriteProtection.Checked = Properties.Settings.Default.OverWriteProtectionEnabled;
            cbSetPrioGame.Checked = Properties.Settings.Default.SetPriorityGame;
            cbSetAffAeq.Checked = Properties.Settings.Default.SetAffinityAequitas;
            cbSetAffGame.Checked = Properties.Settings.Default.SetAffinityGame;
            cbSetAffReminder.Checked = Properties.Settings.Default.SetAffinityquickReminder;
            try { CPUSelAeq.SelectedIndex = Properties.Settings.Default.AffinityAequitas; }
            catch { CPUSelAeq.SelectedIndex = 0; }
            try { CPUSelGame.SelectedIndex = Properties.Settings.Default.AffinityGame; }
            catch { CPUSelGame.SelectedIndex = 0; }
            try { CPUSelReminder.SelectedIndex = Properties.Settings.Default.AffinityquickReminder; }
            catch { CPUSelReminder.SelectedIndex = 0; }

            cbSetAffGame_CheckedChanged(null, null);
            cbSetAffAeq_CheckedChanged(null, null);
            cbSetAffReminder_CheckedChanged(null, null);
            cbActivateHotkey_CheckedChanged(null, null);

            nDemoWarnTime.Value = Properties.Settings.Default.DemoWriteLimit;


            OSDFontSelector.Font = Properties.Settings.Default.OSDFont;
            OSDFontSelector.Color = Properties.Settings.Default.OSDColor;
            cbAutoUpdate.Checked = Properties.Settings.Default.AutoCheckForUpdates;

            lwMatchFilter.Items.Clear();
            foreach (string s in Properties.Settings.Default.MatchFilter)
                lwMatchFilter.Items.Add(s);
            foreach (string s in Properties.Settings.Default.ProcessOptimizerList)
            {
                string[] procargs = s.Split(new string[] { Properties.Settings.Default.ProcessOptimizerListSplitter }, StringSplitOptions.None);
                Row r = new Row();
                r.Cells.Add(new Cell(procargs[0]));
                r.Cells.Add(new Cell(procargs[1]));
                r.Cells.Add(new Cell(procargs[2]));
                int row = tableModel1.Rows.Add(r);
                int cell = 3;
                if (procargs.Length < 4)
                {
                    cell = r.Cells.Add(new Cell("", false));
                }
                else
                {
                    cell = r.Cells.Add(new Cell(string.Empty, Convert.ToBoolean(procargs[3])));
                }
                table1_CellCheckChanged(null, new XPTable.Events.CellCheckBoxEventArgs(tableModel1.Rows[row].Cells[cell], cell, row));
            }
            nCompressionQuality.Value = Properties.Settings.Default.JPGCompressionQuality;
            cbEnableConsoleParsing.Checked = Properties.Settings.Default.EnableConsoleParsing;

            if (Properties.Settings.Default.LanguageString != string.Empty)
            {
                cbLanguageOverride.Checked = true;
                if (Properties.Settings.Default.LanguageString == "de")
                    cbLanguage.SelectedIndex = 0;
                if (Properties.Settings.Default.LanguageString == "en")
                    cbLanguage.SelectedIndex = 1;
            }
            cbModuleTypes.Items.AddRange(Enum.GetNames(typeof(WarnModuleTypes)));
            ArchivePattern.Text = Properties.Settings.Default.ArchivePathTemplate;
            nFreeDiskspaceTreshold.Value = (decimal)Properties.Settings.Default.FreeDiskspaceWarnThreshold;
            cbFileAssociation.Checked = Properties.Settings.Default.CheckQmaAssociation;
            tbAequitasName.Text = Properties.Settings.Default.AequitasTitle;
            RefreshModuleList();
        }

        private void HotkeyIgnore_HotkeyPressed(object sender, EventArgs e)
        {
            MessageBox.Show("HOTKEY PRESSED!");
        }

        private void cbActivateHotkey_CheckedChanged(object sender, EventArgs e)
        {
            HotkeySelector.Enabled = cbActivateHotkey.Checked;
        }

        private void bAddFilter_Click(object sender, EventArgs e)
        {
            ListViewItem i = lwMatchFilter.Items.Add("New filter");
            i.BeginEdit();
        }

        private void bRemove_Click(object sender, EventArgs e)
        {
            while (lwMatchFilter.SelectedItems.Count > 0)
                lwMatchFilter.SelectedItems[0].Remove();
        }

        private void bCheckNow_Click(object sender, EventArgs e)
        {
            try
            {
                if (upd.hasUpdate(Properties.Settings.Default.UpdateURL, new Version(Application.ProductVersion), new UsageInfo(Properties.Settings.Default.PseudoUniqueID, Application.ProductVersion)))
                {
                    if (MessageBox.Show(lang.UpdateAvailable, lang.UpdateAvailableTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        FormUpdate fupd = new FormUpdate(upd);
                        fupd.ShowDialog(this);
                    }
                }
                else
                {
                    MessageBox.Show(lang.GotRecentVersion, string.Empty , MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                Properties.Settings.Default.LastUpdateCheck = DateTime.Now;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
        }

        private void lFilterInfo_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            MessageBox.Show(lang.FilterInfo, lang.FilterInfoTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void table1_BeginEditing(object sender, XPTable.Events.CellEditEventArgs e)
        {
            if (e.Editor is ComboBoxCellEditor)
            {
                ComboBoxCellEditor edit = e.Editor as ComboBoxCellEditor;
                edit.MaxDropDownItems = 10;
                edit.DropDownStyle = DropDownStyle.DropDownList;
                edit.Items.Clear();
                if (e.Column == 0)
                {
                    edit.DropDownStyle = DropDownStyle.DropDown;
                    Process[] procs = Process.GetProcesses();
                    Array.Sort(procs, new ProcessNameComparer());
                    foreach (Process p in procs)
                        if (!edit.Items.Contains(p.ProcessName.ToLower()))
                            edit.Items.Add(p.ProcessName.ToLower());
                    //edit.DroppedDown = true;
                    
                }
                else if (e.Column == 1)
                {
                    /*edit.SelectedIndex = */edit.Items.Add("All CPUs");
                    for (int i=0; i < Environment.ProcessorCount; i++)
                        edit.Items.Add("CPU " + i);
                }
                else if(e.Column == 2)
                {
                    foreach (string s in Enum.GetNames(typeof(ProcessPriorityClass)))
                        edit.Items.Add(s);
                    //edit.SelectedItem = Enum.GetName(typeof(ProcessPriorityClass), ProcessPriorityClass.Normal);
                }
                

                
            }
        }

        private void bAddProgram_Click(object sender, EventArgs e)
        {
            Row r = new Row(new string[] {"", "All CPUs", "Normal" , ""});
            //ComboBoxCellEditor edit = r. as ComboBoxCellEditor;
            table1.EditCell(tableModel1.Rows.Add(r), 0);
            //columnModel1.Columns[0].Ed
        }

        private void bRemoveProgram_Click(object sender, EventArgs e)
        {
            while (tableModel1.Selections.SelectedItems.Length > 0)
                tableModel1.Rows.RemoveAt(tableModel1.Selections.SelectedItems[0].Index);
        }

        private void cbLanguageOverride_CheckedChanged(object sender, EventArgs e)
        {
            cbLanguage.Enabled = cbLanguageOverride.Checked;
        }

        private void table1_CellCheckChanged(object sender, XPTable.Events.CellCheckBoxEventArgs e)
        {
            tableModel1.Rows[e.Row].Cells[1].Enabled = !e.Cell.Checked;
            tableModel1.Rows[e.Row].Cells[2].Enabled = !e.Cell.Checked;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (cbModuleTypes.SelectedItem == null)
                return;
            WarnModule m = WarnModuleCollection.CreateModule((WarnModuleTypes)Enum.Parse(typeof(WarnModuleTypes), (string)cbModuleTypes.SelectedItem));
            WarnModules.AddModule(m);
            tmWarnModules.Rows.Add(createModuleRow(m));
        }

        private Row createModuleRow(WarnModule m)
        {
            Row r = new Row();
            r.Tag = m;
            r.Cells.Add(new Cell(m.Name));
            r.Cells.Add(new Cell(string.Empty, m.isAssigned(WarnEvents.NoAequitas)));
            r.Cells.Add(new Cell(string.Empty, m.isAssigned(WarnEvents.NoReplay)));
            r.Cells.Add(new Cell(string.Empty, m.isAssigned(WarnEvents.TakeStatus)));
            r.Cells.Add(new Cell(string.Empty, m.isAssigned(WarnEvents.RestartReplay)));
            r.Cells.Add(new Cell(string.Empty, m.isAssigned(WarnEvents.LowDiskspace)));
            return r;
        }

        private void bTestModule_Click(object sender, EventArgs e)
        {
            foreach (Row r in tmWarnModules.Selections.SelectedItems)
            {
                try
                {
                    ((OSDWarnModule)r.Tag).Test();
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void table2_SelectionChanged(object sender, XPTable.Events.SelectionEventArgs e)
        {
            if (e.NewSelectedIndicies.Length == 1)
            {
                pgrid.SelectedObject = e.TableModel.Selections.SelectedItems[0].Tag;
                bAboutModule.Enabled = true;
                bTestModule.Enabled = true;
                bRemoveModule.Enabled = true;
                lPropertyTitle.Text = ((WarnModule)e.TableModel.Selections.SelectedItems[0].Tag).Name + " Properties:";
            }
            else
            {
                pgrid.SelectedObject = null;
                bAboutModule.Enabled = false;
                bTestModule.Enabled = false;
                bRemoveModule.Enabled = false;
                lPropertyTitle.Text = "WarnModule Properties:";
            }
        }

        private void table2_CellCheckChanged(object sender, XPTable.Events.CellCheckBoxEventArgs e)
        {
            WarnModule m = tmWarnModules.Rows[e.Row].Tag as WarnModule;
            WarnEvents ev = WarnEvents.None;
            switch (e.Column)
            {
                case 1:
                    ev = WarnEvents.NoAequitas;
                    break;
                case 2:
                    ev = WarnEvents.NoReplay;
                    break;
                case 3:
                    ev = WarnEvents.TakeStatus;
                    break;
                case 4:
                    ev = WarnEvents.RestartReplay;
                    break;
                case 5:
                    ev = WarnEvents.LowDiskspace;
                    break;
            }
            if (e.Cell.Checked)
                m.AssignedEvents |= ev;
            else
                m.AssignedEvents &= ~ev;
        }

        private void bModuleHelp_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start(@"http://enterprising-developers.de/index.php?title=QuickReminder/Readme#Die_verschiedenen_Warnmodule");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bExportModules_Click(object sender, EventArgs e)
        {
            if (ExportDlg.ShowDialog() == DialogResult.OK)
                try
                {
                    WarnModules.Save(ExportDlg.FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.StackTrace, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            
        }

        private void bImportModules_Click(object sender, EventArgs e)
        {
            if (ImportDlg.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    WarnModules.Load(ImportDlg.FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.StackTrace, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                RefreshModuleList();
            }
        }
        private void RefreshModuleList()
        {
            tmWarnModules.Rows.Clear();
            foreach (WarnModule m in WarnModules.Modules)
            {
                tmWarnModules.Rows.Add(createModuleRow(m));
            }
        }

        private void bRemoveModule_Click(object sender, EventArgs e)
        {
            while (tmWarnModules.Selections.SelectedItems.Length > 0)
            {
                WarnModules.RemoveModule((WarnModule)tmWarnModules.Selections.SelectedItems[0].Tag);
                tmWarnModules.Rows.Remove(tmWarnModules.Selections.SelectedItems[0]);
            }
        }

        private void bAboutModule_Click(object sender, EventArgs e)
        {
            foreach (Row r in tmWarnModules.Selections.SelectedItems)
            {
                WarnModule m = r.Tag as WarnModule;
                MessageBox.Show(m.Description, "About " + m.Name, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.ShiftKey && e.KeyCode != Keys.ControlKey)
                richTextBox1_TextChanged(sender, e);
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            int oldstart = ArchivePattern.SelectionStart;
            int oldlen = ArchivePattern.SelectionLength;
            ArchivePattern.SelectAll();
            ArchivePattern.SelectionFont = ArchivePattern.Font;
            foreach(Match m in Regex.Matches(ArchivePattern.Text, "%(ownteam|enemy|league|matchdate|maps)%"))
            {
                ArchivePattern.Select(m.Index, m.Length);
                ArchivePattern.SelectionFont = new Font(ArchivePattern.Font, FontStyle.Bold);
            }
            ArchivePattern.Select(oldstart, oldlen);
        }
	}
    public class ProcessNameComparer : IComparer
    {
        int IComparer.Compare(object a, object b)
        {
            Process c1 = (Process)a;
            Process c2 = (Process)b;
            return c1.ProcessName.CompareTo(c2.ProcessName);
        }
    }

    
}
